package com.yixinsoft.basic.web.taglib;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import org.springframework.util.StringUtils;

/**
 * Created by hqy on 2016/06/16. 
 */
public class PageTag extends TagSupport {
	
	private static final long serialVersionUID = 1L;
	
	private static final int DEFAULT_PAGE_SIZE = 10;

    private int pageIndex;
    private int pageSize;
    private int totalSum;
    private String url;

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public int getPageIndex() {
        return pageIndex;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int ps) {
        this.pageSize = ps;
    }

    public int getTotalSum() {
        return totalSum;
    }

    public void setTotalSum(int totalSum) {
        this.totalSum = totalSum;
    }

    private int getParameterValue(HttpServletRequest request, String name, int defaultValue) {
        String value = request.getParameter(name);
        if (value == null)
            return defaultValue;
        value = value.trim();
        if (value.length() == 0)
            return defaultValue;
        return Integer.parseInt(value);
    }

    @Override
    public int doEndTag() throws JspException {
        if (this.totalSum < 0)
            this.totalSum = 0;

        HttpServletRequest request = ((HttpServletRequest) pageContext.getRequest());
        
        if (pageSize <= 0) {
	        pageSize = getParameterValue(request, "ps", 0);
	        if (pageSize <= 0) {
	        	pageSize = DEFAULT_PAGE_SIZE;
	        }
        }

        int max = (int) Math.ceil((double) this.totalSum / this.pageSize);
        if (max < 1)
            max = 1;

        pageIndex = getParameterValue(request, "p", 1);
        if (pageIndex < 1)
            pageIndex = 1;
        if (pageIndex > max)
            pageIndex = max;

        int next = pageIndex + 1;
        if (next > max)
            next = max;
        if (next < 0)
            next = 0;

        int prev = pageIndex - 1;
        if (prev > max)
            prev = max;
        if (prev < 1)
            prev = 1;


        url = (String) request.getAttribute("javax.servlet.forward.request_uri"); //SpringMVC环境下获取真实请求地址（浏览器地址栏的地址）
        if (url != null) {
            String query = request.getQueryString();
            if (!StringUtils.isEmpty(query))
                url = url + "?" + query;
        } else {
            url = request.getRequestURI();
        }

        Pattern pattern = Pattern.compile("([?&])p=\\d*", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(url);
        boolean containsPage = matcher.find();
        String symbol = containsPage ? matcher.group(1) : url.indexOf('?') == -1 ? "?" : "&";
        JspWriter out = pageContext.getOut();
        try {
            /*out.print("<div class=\"page\"><p>");
            if (prev != pageIndex)
                out.print(String.format("<a href=\"%s\"><</a>", containsPage ? generateUrl(matcher, symbol, prev) : generateUrl(url, symbol, prev)));
            else
                out.print("<strong><</strong>");*/
        	out.print("<div class=\"dataTables_paginate paging_bootstrap\">");
        	out.print("<ul class=\"pagination\">");
        	if (prev != pageIndex) {
        		out.print("<li class=\"prev\">");
    			out.print(String.format("<a href=\"%s\"><i class=\"icon-double-angle-left\" style=\"line-height: inherit\"></i></a>", 
    						containsPage ? generateUrl(matcher, symbol, prev) : generateUrl(url, symbol, prev)));
    			out.print("</li>");
        	} else {
        		out.print("<li class=\"prev disabled\">");
        		out.print("<a href=\"javascript:\"><i class=\"icon-double-angle-left\" style=\"line-height: inherit;\"></i></a>");
        		out.print("</li>");
        	}
        	
            int start = (pageIndex - 1) / 5 * 5;
            for (int i = 1; i <= 5; i++) {
                int pi = start + i;
                if (pi <= max) {
                    if (pi == pageIndex) {
                        //out.print(String.format("<strong class=\"active\">%d</strong>", pi));
                    	out.print(String.format("<li class=\"active\"><a href=\"javascript:\">%d</a>", pi));
            			out.print("</li>");
                    } else {
                        //out.print(String.format("<a href=\"%s\">%d</a>", containsPage ? generateUrl(matcher, symbol, pi) : generateUrl(url, symbol, pi), pi));
                    	out.print(String.format("<li><a href=\"%s\">%d</a>", containsPage ? generateUrl(matcher, symbol, pi) : generateUrl(url, symbol, pi), pi));
                    	out.print("</li>");
                    }
                } else {
                    break;
                }
            }
            if (next != pageIndex) {
                //out.print(String.format("<a href=\"%s\">></a>", containsPage ? generateUrl(matcher, symbol, next) : generateUrl(url, symbol, next)));
            	out.print(String.format("<li class=\"next\"><a href=\"%s\"><i class=\"icon-double-angle-right\" style=\"line-height: inherit;\"></i></a>", containsPage ? generateUrl(matcher, symbol, next) : generateUrl(url, symbol, next)));
            } else {
                //out.print("<strong>></strong>");
            	out.print("<li class=\"next disabled\">");
        		out.print("<a href=\"javascript:\"><i class=\"icon-double-angle-right\" style=\"line-height: inherit;\"></i></a>");
        		out.print("</li>");
            }
            out.print("</ul></div>");
        } catch (IOException e) {
            e.printStackTrace();
            throw new JspException(e);
        }
        return super.doEndTag();
    }

    private String generateUrl(String url, String symbol, int pi) {
        if (pi > 0)
            return url + symbol + "p=" + pi;
        else
            return url;
    }

    private String generateUrl(Matcher matcher, String symbol, int pi) {
        if (pi > 0)
            return matcher.replaceAll(symbol + "p=" + pi);
        else
            return matcher.replaceAll("");
    }

    @Override
    public void release() {
        pageIndex = 0;
        totalSum = 0;
        pageSize = 10;

        super.release();
    }
	
}
